import Toast from 'tdesign-miniprogram/toast/index';
import request from '../../../../utils/requestAdmin';


Page({
  data: {
    originFiles: [
    ],
    successNum: 0,

    id: 0,
    brandId: '',
    seriesId: '',
    specId: '',
    carName: '',
    vin: '',
    status: 1,
    carImages: [],
    carDesc: '',
    flag: 0,
    shopId: '0',
    gridConfig: {
      column: 4,
      width: 160,
      height: 160,
    },
    config: {
      count: 1,
    },
    pickerVisible: false,
    pickerValue: [],
    pickerType: 'brand',
    pickerList: [],
    brands: [],
    series: [],
    specs: []

  },
  privateData: {
    verifyTips: '',
  },
  onLoad(options) {
    const { id } = options;
    console.log("aaaaaaaa")
    var currentCar = getApp().globalData.currentCar;
    if (currentCar != null) {
      if (currentCar.id == id) {
        var files = []
        var carImgs = currentCar.carImages;
        // if (currentCar.carImages != null && currentCar.carImages.length > 0) {
        //   carImgs = currentCar.carImages.split(',');
        // }
        if (carImgs != null) {
          for (var i = 0; i < carImgs.length; i++) {
            files.push({ url: carImgs[i] })
          }
        }
        this.setData({
          brandId: currentCar.brandId,
          brandName: currentCar.brandName,
          carDesc: currentCar.carDesc,
          seriesId: currentCar.seriesId,
          seriesName: currentCar.seriesName,
          specId: currentCar.specId,
          specName: currentCar.specName,
          carName: currentCar.carName,
          vin: currentCar.vin,
          originFiles: files
        })
      } else {
        getApp().globalData.currentCar = null;
      }
    }
    this.setData({ id: id });
  },

  handleSuccess(e) {
    const { files } = e.detail;
    console.log("success", files)
    this.setData({
      originFiles: files,
    });
  },
  handleRemove(e) {
    const { index } = e.detail;
    const { originFiles } = this.data;
    originFiles.splice(index, 1);
    this.setData({
      originFiles,
    });
  },
  handleClick(e) {
    console.log(e.detail.file);
  },

  hasSava: false,

  onInputValue(e) {
    const { item } = e.currentTarget.dataset;
    const { value = '' } = e.detail;
    this.setData(
      {
        [`${item}`]: value,
      },
      () => {
        const { isLegal, tips } = this.onVerifyInputLegal();
        this.setData({
          submitActive: isLegal,
        });
        this.privateData.verifyTips = tips;
      },
    );
  },
  onColumnChange(e) {
    console.log('picker pick:', e);
  },

  onPickerChange(e) {
    const { value, label } = e.detail;
    console.log(e.detail)
    var key = this.data.pickerType;
    this.setData({
      pickerValue: false,
      [`${key}Id`]: value[0],
      [`${key}Name`]: label[0],
    });
  },

  onPickerCancel(e) {
    this.setData({ pickerValue: false });
  },

  onBrandPicker() {
    var that = this;
    request.get("car/rule/getCarBrand", null, function (res) {
      if (res.code == 0) {
        var list = [];
        for (var i = 0; i < res.data.length; i++) {
          list.push({ label: res.data[i].title, value: res.data[i].id })
        }
        that.setData({ pickerType: 'brand', pickerVisible: true, pickerList: list });
      } else {
        wx.showModal({ title: '提示', content: res.message, showCancel: false });
      }
    })
  },
  onSeriesPicker() {
    var that = this;
    if (this.data.brandId == 0) {
      wx.showToast({
        title: '请选择选择品牌',
      })
      return;
    }
    request.get("car/rule/getCarSeries?brandId=" + this.data.brandId, null, function (res) {
      if (res.code == 0) {
        var list = [];
        for (var i = 0; i < res.data.length; i++) {
          list.push({ label: res.data[i].title, value: res.data[i].id })
        }
        that.setData({ pickerType: 'series', pickerVisible: true, pickerList: list });
      } else {
        wx.showModal({ title: '提示', content: res.message, showCancel: false });
      }
    })
  },
  onSpecPicker() {
    var that = this;
    if (this.data.seriesId == 0) {
      wx.showToast({
        title: '请选择选择车系',
      })
      return;
    }
    request.get("car/rule/getCarSpec?seriesId=" + this.data.seriesId, null, function (res) {
      if (res.code == 0) {
        var list = [];
        for (var i = 0; i < res.data.length; i++) {
          list.push({ label: res.data[i].title, value: res.data[i].id })
        }
        that.setData({ pickerType: 'spec', pickerVisible: true, pickerList: list });
      } else {
        wx.showModal({ title: '提示', content: res.message, showCancel: false });
      }
    })
  },


  onVerifyInputLegal() {
    const { brandId, seriesId, vin } = this.data;

    if (brandId == '' || brandId == 0) {
      return {
        isLegal: false,
        tips: '请选择品牌',
      };
    }
    if (seriesId == '' || seriesId == 0) {
      return {
        isLegal: false,
        tips: '请选择车系',
      };
    }
    if (vin == '') {
      return {
        isLegal: false,
        tips: '请填写VIN',
      };
    }
    return {
      isLegal: true,
      tips: '提交成功',
    };
  },

  formSubmit() {
    var that = this;
    this.setData({ evaImages: [] })
    const { submitActive, originFiles } = this.data;
    const { isLegal, tips } = this.onVerifyInputLegal();
    if (!isLegal) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: tips,
        icon: '',
        duration: 1000,
      });
      return;
    }
    //upload image
    if (originFiles.length > 0) {
      originFiles.forEach(file => this.uploadFile(file))
    } else {
      this.saveEva();
    }
  },
  uploadFile(file) {
    var that = this;
    if (file.url.indexOf(getApp().globalData.imageUrl) != -1) {
      var carImages = that.data.carImages;
      carImages.push(file.url.replace(getApp().globalData.imageUrl, ''));
      that.setData({ carImages: carImages })
      if (carImages.length == that.data.originFiles.length) {
        that.saveEva();
      }
    } else {
      wx.compressImage({
        src: file.url,
        quality: 70,
        //   compressedWidth:400,
        success(res) {
          console.log("压缩成功，上传", res.tempFilePath)
          that.uploadServer(res.tempFilePath)
        },
        fail() {
          console.log("压缩失败，上传", file.url)
          that.uploadServer(file.url)
        }
      })
    }
  },
  uploadServer(tempPhotoUrl) {
    var that = this;
    wx.showToast({ icon: "loading", title: "正在上传……" });
    that.setData({ uploading: true })
    request.upload('/car/admin/uploadFile', tempPhotoUrl, function (res) {
      that.setData({ uploading: false })
      if (res.code == 0) {
        var carImages = that.data.carImages;
        carImages.push(res.data);
        that.setData({ carImages: carImages })
        if (carImages.length == that.data.originFiles.length) {
          that.saveEva();
        }
      } else {
        // wx.showModal({ title: '提示', content: '图片上传', showCancel: false });
        console.log("图片上传失败", res.message);
      }
    })
  },
  saveEva() {
    var that = this;
    var carImages = '';
    for (var i = 0; i < this.data.carImages.length; i++) {
      if (carImages.length > 0) carImages = carImages + ",";
      carImages = carImages + this.data.carImages[i];
    }
    var url = "/car/admin/stock/addStock"
    if (this.data.id > 0) url = 'car/admin/stock/editStock'
    var data = {
      id: this.data.id,
      carDesc: this.data.carDesc,
      carImages: carImages,
      brandId: this.data.brandId,
      seriesId: this.data.seriesId,
      specId: this.data.specId,
      carName: this.data.carName,
      vin: this.data.vin
    }
    request.post(url, data, function (res) {
      if (res.code == 0) {
        that.hasSava = true;
        wx.navigateBack({ delta: 1 });
      } else {
        wx.showModal({ title: '提示', content: res.message, showCancel: false });
      }
    })
  }
});
